<template>
  <div class="register-page">
    <div class="register-container">
      <div class="register-box">
        <div class="register-header">
          <h2>欢迎注册</h2>
        </div>

        <div class="register-form">
          <div class="form-group">
            <input type="text" placeholder="用户名" v-model="username" class="form-control">
            <span class="check-icon" v-if="username && !usernameError">✓</span>
            <div class="error-message" v-if="usernameError">{{ usernameError }}</div>
          </div>
          <div class="form-group password-group">
            <div class="password-input-container">
              <input 
                :type="showPassword ? 'text' : 'password'" 
                placeholder="密码" 
                v-model="password" 
                class="form-control"
                @blur="validatePassword"
              >
              <span 
                class="password-toggle" 
                @click="togglePasswordVisibility"
              >
                {{ showPassword ? '👁️' : '👁️‍🗨️' }}
              </span>
            </div>
            <div class="password-requirements">
              <small>密码要求：8-16位，包含数字、字母、特殊符号</small>
              <div class="password-strength" v-if="password">
                <div class="strength-indicator">
                  <span :class="['strength-item', { active: hasMinLength }]">长度8-16位</span>
                  <span :class="['strength-item', { active: hasNumber }]">包含数字</span>
                  <span :class="['strength-item', { active: hasLetter }]">包含字母</span>
                  <span :class="['strength-item', { active: hasSpecialChar }]">包含特殊符号</span>
                </div>
              </div>
            </div>
            <div class="error-message" v-if="passwordError">{{ passwordError }}</div>
          </div>
          <div class="form-group password-group">
            <div class="password-input-container">
              <input 
                :type="showConfirmPassword ? 'text' : 'password'" 
                placeholder="确认密码" 
                v-model="confirmPassword" 
                class="form-control"
                @blur="validateConfirmPassword"
              >
              <span 
                class="password-toggle" 
                @click="toggleConfirmPasswordVisibility"
              >
                {{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
              </span>
            </div>
            <div class="error-message" v-if="confirmPasswordError">{{ confirmPasswordError }}</div>
          </div>
          <div class="form-group">
            <div class="phone-input">
              <input type="email" placeholder="输入邮箱" v-model="email" class="form-control email-control" @blur="validateEmail">
            </div>
            <div class="error-message" v-if="emailError">{{ emailError }}</div>
          </div>
          <div class="form-group verification-group">
            <input type="text" placeholder="请输入邮箱验证码" v-model="verificationCode" class="form-control verification-control" @blur="validateVerificationCode" maxlength="10">
            <button class="verification-btn" @click="showCaptchaModal">获取验证码</button>
          </div>
          <div class="error-message" v-if="verificationCodeError">{{ verificationCodeError }}</div>
          <div class="register-submit">
            <button class="register-btn" @click="submitRegister" :disabled="isRegistering">
              <span v-if="isRegistering" class="loading-spinner"></span>
              <span v-else>立即注册</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 图形验证码弹窗 -->
  <div class="captcha-modal" v-if="captchaModalVisible">
    <div class="captcha-container">
      <div class="captcha-header">
        <h3>请完成验证</h3>
        <span class="close-btn" @click="closeCaptchaModal">&times;</span>
      </div>
      <div class="captcha-content">
        <div class="captcha-image-container">
          <img :src="captchaImage" alt="验证码" class="captcha-image" v-if="captchaImage" @error="onImageError" @load="onImageLoad">
          <div class="captcha-loading" v-else>加载中...</div>

        </div>
        <div class="captcha-input-group">
          <input type="text" placeholder="请输入验证码" v-model="captchaCode" class="captcha-input">
        </div>
      </div>
              <div class="captcha-footer">
          <button class="captcha-refresh-btn" @click="refreshCaptcha">
            <i class="refresh-icon">↻</i> 换一张
          </button>
          <button class="captcha-confirm-btn" @click="verifyCaptcha">确认</button>
        </div>
    </div>
  </div>
  
  <!-- 邮箱验证码发送状态提示 -->
  <div class="email-sending-modal" v-if="isSendingEmail">
    <div class="email-sending-container">
      <div class="email-sending-content">
        <div class="loading-spinner-large"></div>
        <h3>正在发送邮箱验证码...</h3>
        <p>请稍候，验证码将发送到 {{ email }}</p>
        <p v-if="emailSendRetryCount > 0" class="retry-info">正在重试 (第{{ emailSendRetryCount }}次)</p>
      </div>
    </div>
  </div>
</template>

<script>
import { userApi } from '@/api'
import logger from '../utils/logger.js'

export default {
  name: 'RegisterView',
  data() {
    return {
      username: '',
      password: '',
      confirmPassword: '',
      email: '',
      verificationCode: '',
      showPassword: false,
      showConfirmPassword: false,
      usernameError: '',
      passwordError: '',
      confirmPasswordError: '',
      emailError: '',
      verificationCodeError: '',
      captchaModalVisible: false,
      captchaImage: '',
      captchaCode: '',
      captchaLoading: false,
      isRegistering: false,
      captchaId: null, // 新增：用于存储验证码ID
      isSendingEmail: false, // 新增：用于显示邮箱验证码发送状态
      emailSendRetryCount: 0 // 新增：重试次数显示
          };
    },
    computed: {
      // 密码强度检查
      hasMinLength() {
        return this.password && this.password.length >= 8 && this.password.length <= 16;
      },
      hasNumber() {
        return this.password && /\d/.test(this.password);
      },
      hasLetter() {
        return this.password && /[a-zA-Z]/.test(this.password);
      },
      hasSpecialChar() {
        return this.password && /[!@#$%^&*(),.?":{}|<>]/.test(this.password);
      }
    },
  methods: {
    validateUsername() {
      if (!this.username) {
        this.usernameError = '请输入账号';
        return false;
      } else if (this.username.length < 3) {
        this.usernameError = '账号长度不能少于3个字符';
        return false;
      } else {
        this.usernameError = '';
        return true;
      }
    },
    validatePassword() {
      if (!this.password) {
        this.passwordError = '请输入密码';
        return false;
      }
      
      // 检查密码长度 (8-16位)
      if (this.password.length < 8 || this.password.length > 16) {
        this.passwordError = '密码长度必须在8-16位之间';
        return false;
      }
      
      // 检查是否包含数字
      if (!/\d/.test(this.password)) {
        this.passwordError = '密码必须包含至少一个数字';
        return false;
      }
      
      // 检查是否包含字母
      if (!/[a-zA-Z]/.test(this.password)) {
        this.passwordError = '密码必须包含至少一个字母';
        return false;
      }
      
      // 检查是否包含特殊符号
      if (!/[!@#$%^&*(),.?":{}|<>]/.test(this.password)) {
        this.passwordError = '密码必须包含至少一个特殊符号(!@#$%^&*(),.?":{}|<>)';
        return false;
      }
      
      this.passwordError = '';
      // 如果确认密码已填写，重新验证确认密码
      if (this.confirmPassword) {
        this.validateConfirmPassword();
      }
      return true;
    },
    validateConfirmPassword() {
      if (!this.confirmPassword) {
        this.confirmPasswordError = '请确认密码';
        return false;
      } else if (this.confirmPassword !== this.password) {
        this.confirmPasswordError = '两次输入的密码不一致';
        return false;
      } else {
        this.confirmPasswordError = '';
        return true;
      }
    },
    validateEmail() {
      if (!this.email) {
        this.emailError = '请输入邮箱';
        return false;
      }
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(this.email)) {
        this.emailError = '请输入有效的邮箱地址';
        return false;
      }
      this.emailError = '';
      return true;
    },
    validateVerificationCode() {
      if (!this.verificationCode) {
        this.verificationCodeError = '请输入验证码';
        return false;
      }
      if (this.verificationCode.length < 4 || this.verificationCode.length > 10) {
        this.verificationCodeError = '验证码应为4-10位数字';
        return false;
      }
      // 验证是否为纯数字
      if (!/^\d+$/.test(this.verificationCode)) {
        this.verificationCodeError = '验证码只能包含数字';
        return false;
      }
      this.verificationCodeError = '';
      return true;
    },
    validateCaptchaCode() {
      if (!this.captchaCode) {
        alert('请先完成图形验证码验证');
        return false;
      }
      if (!this.captchaId) {
        alert('验证码已过期，请重新获取');
        return false;
      }
      return true;
    },
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    toggleConfirmPasswordVisibility() {
      this.showConfirmPassword = !this.showConfirmPassword;
    },
    async submitRegister() {
      // 验证所有字段
      const isUsernameValid = this.validateUsername();
      const isPasswordValid = this.validatePassword();
      const isConfirmPasswordValid = this.validateConfirmPassword();
      const isEmailValid = this.validateEmail();
      const isVerificationCodeValid = this.validateVerificationCode();
      const isCaptchaValid = this.validateCaptchaCode();
      
      if (!isUsernameValid || !isPasswordValid || !isConfirmPasswordValid || !isEmailValid || !isVerificationCodeValid || !isCaptchaValid) {
        return; // 如果验证失败，不继续处理
      }
      
      this.isRegistering = true;
      
      try {
        // 调用注册API - 使用后端期望的精确格式
        const registerData = {
          userName: this.username,       // 用户名 (必需)
          account: this.email,           // 邮箱账号 (必需)
          password: this.password,       // 密码 (必需)
          code: this.verificationCode    // 邮箱验证码 (必需)
        };
        
                      logger.log('🚀 发送注册请求数据 (POST + Query参数格式):', registerData);
        logger.log('📋 注册参数详情:');
        logger.log('  - userName:', registerData.userName);
        logger.log('  - account:', registerData.account);
        logger.log('  - password:', registerData.password);
        logger.log('  - code:', registerData.code, '长度:', registerData.code?.length);
        
        // 验证必需字段
        const missingFields = [];
        if (!this.email) missingFields.push('邮箱');
        if (!this.password) missingFields.push('密码');
        if (!this.verificationCode) missingFields.push('邮箱验证码');
        if (!this.username) missingFields.push('用户名');
        
        if (missingFields.length > 0) {
          alert(`请填写以下必需字段: ${missingFields.join(', ')}`);
          return;
        }
        
        logger.log('✅ 所有必需字段都已填写');
        
        const response = await userApi.register(registerData);
        
        logger.log('🎉 注册API响应:', response);
        
        // 检查后端返回的code字段来判断注册是否成功
        // code为0表示成功，code为1或其他非0值表示失败
        if (response.code !== 0) {
          logger.error('❌ 注册失败:', response.message);
          alert(`注册失败：${response.message}`);
          return;
        }
        
        logger.log('✅ 注册成功!');
        
        // 注册成功后，保存用户信息（不包含密码）
        const userInfo = {
          username: this.username || this.email.split('@')[0],
          email: this.email,
          account: this.email,
          // 不保存密码，安全考虑
          avatar: response?.data?.avatar || response?.avatar || '',
          id: response?.data?.id || response?.id || Date.now(), // 如果后端没返回ID，生成一个
          role: response?.data?.role || response?.role || 'user',
          nickname: this.username || this.email.split('@')[0],
          registerTime: new Date().toISOString(),
          _source: 'registration'
        };
        
        // 保存用户信息到localStorage，供登录后使用
        localStorage.setItem('userProfile', JSON.stringify(userInfo));
        
        // 同时保存一个简单的注册标记，包含邮箱用于登录页面填充
        const loginHint = {
          email: this.email,
          justRegistered: true
        };
        localStorage.setItem('loginHint', JSON.stringify(loginHint));
        
        logger.log('✅ 用户信息已保存:', userInfo);
        logger.log('✅ 登录提示已保存:', loginHint);
        
        alert('注册成功！请登录以完成认证...');
        
        // 跳转到登录页面
        setTimeout(() => {
          this.$router.push('/login');
        }, 500);
        
      } catch (error) {
        logger.error('❌ 注册失败:', error);
        logger.error('❌ 错误详情:', error.response?.data);
        
        // 显示具体的错误信息
        let errorMessage = '注册失败，请重试';
        if (error.response?.data?.message) {
          errorMessage = error.response.data.message;
        } else if (error.message) {
          errorMessage = error.message;
        }
        
        alert(errorMessage);
        
        // 如果是验证码错误，可能需要重新获取验证码
        if (errorMessage.includes('验证码') || errorMessage.includes('code')) {
          logger.log('🔄 验证码相关错误，建议重新获取验证码');
        }
      } finally {
        this.isRegistering = false;
      }
    },
    async sendVerificationCode() {
      // 验证邮箱格式
      if (!this.validateEmail()) {
        logger.warn('⚠️ 邮箱格式验证失败');
        return;
      }
      
      this.isSendingEmail = true; // 开始发送状态
      this.emailSendRetryCount = 0; // 重置重试计数
      
      try {
        logger.log('开始发送邮箱验证码到:', this.email);
        
        // 调用后端API发送邮箱验证码
        const emailData = {
          email: this.email,
          toEmail: this.email,           // 后端可能期望的邮箱字段名
          // 图形验证码验证信息 - 包含后端期望的所有字段格式
          code: this.captchaCode,        // 通用验证码字段
          captcha: this.captchaCode,     // 后端可能期望的字段
          captchaCode: this.captchaCode, // 标准验证码字段
          uuid: this.captchaId,          // 通用UUID字段
          captchaId: this.captchaId,     // 标准ID字段
          captchaUuid: this.captchaId    // 后端实际使用的UUID字段
        };
        
        logger.log('📧 发送请求数据:', emailData);
        logger.log('🔍 验证码详情 - Code:', emailData.code, 'UUID:', emailData.uuid);
        logger.log('🔍 验证所有参数值:');
        logger.log('  - email:', emailData.email);
        logger.log('  - toEmail:', emailData.toEmail);
        logger.log('  - captchaCode:', emailData.captchaCode);
        logger.log('  - captcha:', emailData.captcha);
        logger.log('  - captchaId:', emailData.captchaId);
        logger.log('  - captchaUuid:', emailData.captchaUuid);
        logger.log('  - code:', emailData.code);
        logger.log('  - uuid:', emailData.uuid);
        
        // 检查关键参数是否为空
        if (!emailData.email) {
          alert('邮箱地址为空，请先输入邮箱');
          return;
        }
        if (!emailData.captchaCode) {
          alert('图形验证码为空，请先完成图形验证码验证');
          this.showCaptchaModal();
          return;
        }
        if (!emailData.captchaId) {
          alert('验证码ID丢失，请重新获取验证码');
          this.showCaptchaModal();
          return;
        }
        
        const response = await userApi.sendEmailCode(emailData, (retryCount) => {
          this.emailSendRetryCount = retryCount;
        });
        
        logger.log('📧 邮箱验证码API响应:', response);
        
        if (response && (response.success || response.code === 200 || response.status === 'success' || response.data)) {
          logger.log('邮箱验证码发送成功');
          alert('验证码已发送到您的邮箱，请查收');
        } else {
          logger.warn('⚠️ 邮箱验证码发送响应异常:', response);
          
          // 特殊处理图形验证码错误
          if (response && (response.message === '图形验证码错误' || response.message.includes('验证码'))) {
            alert(`图形验证码验证失败！\n\n您输入的验证码：${this.captchaCode}\n错误原因：${response.message}\n\n解决方法：\n1. 点击"换一张"获取新验证码\n2. 仔细对比图片，准确输入\n3. 注意区分相似字符(如I/1, O/0)\n4. 可能区分大小写`);
            // 清空错误的验证码并重新显示验证码弹窗
            this.captchaCode = '';
            this.showCaptchaModal();
          } else {
            alert(response.message || response.msg || '发送验证码失败，请稍后重试');
          }
        }
              } catch (error) {
          logger.error('❌ 邮箱验证码发送失败:', error);
          logger.error('❌ 错误详情:', error.response || error.message);
          
          // 特殊处理：图形验证码错误
          if (error.isBusinessError && error.message === '需要先验证图形验证码') {
            alert('需要先完成图形验证码验证\n请点击"获取验证码"按钮完成验证');
            return; // 不继续处理，让用户去完成图形验证码
          }
          
          // 根据错误类型提供不同的提示
          if (error.response && error.response.status === 404) {
            alert('邮箱验证码接口不存在\n请联系管理员确认正确的接口路径\n\n临时解决：您可以直接输入任意5位数字作为验证码继续注册流程');
          } else if (error.response && error.response.status === 400) {
            alert('请求参数有误，请重试');
          } else if (error.response && error.response.status === 500) {
            alert('服务器错误，请稍后重试');
          } else if (error.code === 'NETWORK_ERROR') {
            alert('网络连接失败，请检查网络');
          } else {
            // 降级处理：提供临时解决方案
            alert('邮箱验证码发送接口暂时不可用\n\n临时解决：您可以直接输入任意5位数字作为验证码继续注册流程');
          }
        } finally {
        this.isSendingEmail = false; // 结束发送状态
      }
    },
    showCaptchaModal() {
      // 在显示验证码弹窗前先验证邮箱格式
      if (!this.validateEmail()) {
        logger.warn('⚠️ 邮箱格式验证失败，无法获取验证码');
        return;
      }
      
      logger.log('📧 邮箱验证通过，准备显示图形验证码弹窗');
      logger.log('📧 当前邮箱地址:', this.email);
      
      this.captchaModalVisible = true;
      this.loadCaptcha();
    },
    closeCaptchaModal() {
      this.captchaModalVisible = false;
      this.captchaCode = '';
    },
    hideCaptchaModal() {
      // 只隐藏弹窗，不清空验证码
      this.captchaModalVisible = false;
    },
    async loadCaptcha() {
      this.captchaLoading = true;
      this.captchaImage = '';
      
      try {
        logger.log('🔄 开始加载验证码...');
        
        const response = await userApi.getCaptcha();
        logger.log('📨 验证码API响应:', response);
        
        // 根据实际API响应格式处理数据: {"img": "base64string", "uuid": "验证码ID"}
        let imageData = null;
        let captchaId = null;
        
        if (response && typeof response === 'object') {
          // 处理后端实际返回的数据格式: {captcha: "base64", captchaUuid: "uuid"}
          if (response.captcha && response.captchaUuid) {
            imageData = response.captcha;
            captchaId = response.captchaUuid;
            logger.log('✅ 检测到后端标准格式: captcha + captchaUuid');
          }
          // 优先处理标准格式: {img: "base64", uuid: "id"}
          else if (response.img) {
            imageData = response.img;
            captchaId = response.uuid || response.id || response.captchaId || response.captchaUuid;
          }
          // 处理嵌套在data中的格式
          else if (response.data && response.data.img) {
            imageData = response.data.img;
            captchaId = response.data.uuid || response.data.id || response.data.captchaId || response.data.captchaUuid;
          }
          // 处理嵌套在data中的后端格式
          else if (response.data && response.data.captcha && response.data.captchaUuid) {
            imageData = response.data.captcha;
            captchaId = response.data.captchaUuid;
            logger.log('✅ 检测到嵌套的后端标准格式: data.captcha + data.captchaUuid');
          }
          // 处理其他可能的字段名
          else if (response.image || response.captcha) {
            imageData = response.image || response.captcha;
            captchaId = response.uuid || response.id || response.captchaId || response.captchaUuid;
          }
        }
        
        logger.log('🔍 提取的数据 - imageData存在:', !!imageData);
        logger.log('🔍 提取的数据 - captchaId:', captchaId);
        
        if (imageData) {
          logger.log('🔍 原始验证码数据类型:', typeof imageData);
          logger.log('🔍 原始验证码数据长度:', imageData.length);
          logger.log('🔍 原始验证码数据前100字符:', imageData.substring(0, 100));
          
          // 使用增强的处理方法
          const finalImageUrl = this.processBase64Image(imageData);
          
          if (!finalImageUrl) {
            throw new Error('验证码图片处理失败');
          }
          
          this.captchaImage = finalImageUrl;
          this.captchaId = captchaId || Date.now().toString(); // 使用时间戳作为默认ID
          
          logger.log('✅ 验证码加载成功!');
          logger.log('🆔 验证码ID:', this.captchaId);
          logger.log('🖼️ 最终图片URL长度:', finalImageUrl.length);
          logger.log('🖼️ 最终图片URL前缀:', finalImageUrl.substring(0, 50));
          
          // 添加一个测试方法：将base64数据输出到控制台，方便使用外部工具验证
          if (imageData && !imageData.startsWith('data:image/') && !imageData.startsWith('http')) {
            const cleanBase64 = imageData.replace(/[\s\n\r\t]/g, '');
            logger.log('🔬 用于外部验证的纯base64数据:');
            logger.log('📋 复制以下内容到 https://base64.guru/converter/decode/image/png 进行验证:');
            logger.log(cleanBase64);
          }
          
        } else {
          throw new Error('未找到验证码图片数据');
        }
        
      } catch (error) {
        logger.error('❌ 验证码加载失败:', error);
        
        // 显示错误提示但不影响用户继续操作
        alert('验证码加载失败，请重试');
        
        // 关闭弹窗
        this.closeCaptchaModal();
      } finally {
        this.captchaLoading = false;
      }
    },
    refreshCaptcha() {
      this.loadCaptcha();
    },

    processBase64Image(data) {
      // 增强的base64处理方法，包含详细调试信息
      if (!data) {
        logger.error('❌ processBase64Image: 数据为空');
        return '';
      }
      
      logger.log('🔍 processBase64Image 输入数据类型:', typeof data);
      logger.log('🔍 processBase64Image 输入数据长度:', data.length);
      logger.log('🔍 processBase64Image 输入数据前50字符:', data.substring(0, 50));
      
      // 如果已经是完整的data URI
      if (data.startsWith('data:image/')) {
        logger.log('✅ 检测到完整的data URI');
        return data;
      }
      
      // 如果是HTTP/HTTPS URL
      if (data.startsWith('http')) {
        logger.log('✅ 检测到HTTP URL');
        return data;
      }
      
      // 处理纯base64字符串
      logger.log('🔧 处理纯base64字符串...');
      
      // 更彻底的清理：移除所有空白字符、换行符等
      const cleanBase64 = data.replace(/[\s\n\r\t]/g, '');
      logger.log('🔧 清理后的base64长度:', cleanBase64.length);
      
      // 验证base64格式
      const base64Pattern = /^[A-Za-z0-9+/]*={0,2}$/;
      if (!base64Pattern.test(cleanBase64)) {
        logger.warn('⚠️ base64格式可能不正确');
        logger.log('🔍 可疑字符:', cleanBase64.match(/[^A-Za-z0-9+/=]/g));
      }
      
      // 默认使用PNG格式
      let finalDataUri = `data:image/png;base64,${cleanBase64}`;
      logger.log('🖼️ 生成的data URI前100字符:', finalDataUri.substring(0, 100));
      
      // 可选：添加base64验证
      try {
        // 尝试解码base64以验证其有效性
        const binaryString = atob(cleanBase64);
        logger.log('✅ base64解码成功，二进制数据长度:', binaryString.length);
        
        // 检查PNG文件头
        const pngHeader = binaryString.substring(0, 8);
        const pngSignature = '\x89PNG\r\n\x1a\n';
        if (pngHeader === pngSignature) {
          logger.log('✅ 确认为PNG格式');
        } else {
          logger.log('⚠️ 可能不是PNG格式，文件头:', Array.from(pngHeader).map(c => c.charCodeAt(0).toString(16)).join(' '));
          // 尝试JPEG格式
          if (binaryString.charCodeAt(0) === 0xFF && binaryString.charCodeAt(1) === 0xD8) {
            logger.log('🔄 检测到JPEG格式，切换为JPEG');
            finalDataUri = `data:image/jpeg;base64,${cleanBase64}`;
          }
        }
      } catch (decodeError) {
        logger.error('❌ base64解码失败:', decodeError);
        logger.log('🔍 原始base64数据（前200字符）:', cleanBase64.substring(0, 200));
      }
      
      return finalDataUri;
    },
    onImageLoad() {
      logger.log('✅ 验证码图片加载成功');
    },
    onImageError(event) {
      logger.error('❌ 验证码图片加载失败:', event);
      logger.error('❌ 图片src长度:', event.target.src.length);
      logger.error('❌ 图片src前100字符:', event.target.src.substring(0, 100));
      logger.error('❌ 图片src后100字符:', event.target.src.substring(event.target.src.length - 100));
      
      // 尝试分析失败原因
      const src = event.target.src;
      if (src.startsWith('data:image/')) {
        const parts = src.split(',');
        if (parts.length === 2) {
          const base64Part = parts[1];
          logger.error('🔍 base64部分长度:', base64Part.length);
          logger.error('🔍 base64前50字符:', base64Part.substring(0, 50));
          
          // 验证base64格式
          const base64Pattern = /^[A-Za-z0-9+/]*={0,2}$/;
          if (!base64Pattern.test(base64Part)) {
            logger.error('❌ base64格式不正确');
            const invalidChars = base64Part.match(/[^A-Za-z0-9+/=]/g);
            logger.error('🔍 非法字符:', invalidChars);
          } else {
            logger.log('✅ base64格式看起来正确');
          }
          
          // 尝试解码验证
          try {
            const decoded = atob(base64Part);
            logger.log('✅ base64解码成功，解码后长度:', decoded.length);
          } catch (decodeError) {
            logger.error('❌ base64解码失败:', decodeError);
          }
        }
      }
      
      // 提供调试建议
      logger.log('🔧 调试建议:');
      logger.log('1. 复制控制台中的纯base64数据到 https://base64.guru/converter/decode/image/png 验证');
      logger.log('2. 检查后端返回的数据格式是否正确');
      logger.log('3. 确认图片格式是否为PNG或其他支持的格式');
    },
    async verifyCaptcha() {
      // 首先验证邮箱是否填写正确
      if (!this.email) {
        alert('请先填写邮箱地址');
        return;
      }
      
      if (!this.validateEmail()) {
        alert('请填写有效的邮箱地址');
        return;
      }
      
      // 验证图像验证码输入
      if (!this.captchaCode) {
        alert('请输入验证码');
        return;
      }
      
      if (!this.captchaId) {
        alert('验证码ID丢失，请重新获取验证码');
        this.refreshCaptcha();
        return;
      }
      
      logger.log('🔐 开始验证图形验证码...');
      logger.log('🔐 当前图形验证码:', this.captchaCode);
      logger.log('🆔 当前验证码ID:', this.captchaId);
      
      try {
        // 准备验证数据 - 包含后端可能期望的所有字段格式
        const verifyData = {
          code: this.captchaCode,           // 通用字段
          captcha: this.captchaCode,        // 后端可能期望的字段
          captchaCode: this.captchaCode,    // 标准字段
          uuid: this.captchaId,             // 通用UUID字段
          captchaId: this.captchaId,        // 标准ID字段
          captchaUuid: this.captchaId       // 后端实际使用的字段
        };
        
        logger.log('🔐 发送验证数据:', verifyData);
        
        // 构建发送邮件验证码的请求数据
        const emailCodeData = {
          toEmail: this.email,
          captcha: this.captchaCode,
          captchaUuid: this.captchaId
        };
        
        logger.log('📧 发送邮件验证码数据:', emailCodeData);
        
        // 调用发送邮件验证码接口（同时验证图形验证码）
        const response = await userApi.sendEmailCode(emailCodeData);
        
        logger.log('✅ 邮件验证码发送成功！', response);
        
        // 验证成功后隐藏弹窗
        this.hideCaptchaModal();
        
        // 显示成功消息
        alert('验证码已发送到您的邮箱，请查收！');
        
      } catch (error) {
        logger.error('❌ 发送邮件验证码失败:', error);
        
        // 处理不同类型的错误
        if (error.message) {
          alert(error.message);
        } else if (error.response && error.response.status === 400) {
          alert('验证码错误，请重新输入');
        } else if (error.response && error.response.status === 404) {
          alert('验证码已过期，请重新获取');
          this.refreshCaptcha();
        } else {
          alert('验证码验证失败，请重试');
        }
        
        // 清空输入的验证码，让用户重新输入
        this.captchaCode = '';
      }
    }
  },
  mounted() {
    logger.log('注册页面已加载!');
  }
};
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #e6f0fd 0%, #d9e8ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.register-container {
  width: 100%;
  max-width: 400px;
  padding: 20px;
}

.register-box {
  width: 100%;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.register-header {
  margin-bottom: 30px;
  text-align: center;
}

.register-header h2 {
  font-size: 24px;
  color: #333;
  font-weight: normal;
}

.register-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-control {
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 16px;
  background-color: #f5f8ff;
  box-sizing: border-box;
}

.error-message {
  color: #f44336;
  font-size: 12px;
  margin-top: 5px;
}

.password-requirements {
  margin-top: 5px;
  margin-bottom: 5px;
}

.password-requirements small {
  color: #6c757d;
  font-size: 11px;
  line-height: 1.2;
}

.password-strength {
  margin-top: 8px;
}

.strength-indicator {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.strength-item {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 3px;
  background-color: #f8f9fa;
  color: #6c757d;
  border: 1px solid #e9ecef;
  transition: all 0.2s ease;
}

.strength-item.active {
  background-color: #d4edda;
  color: #155724;
  border-color: #c3e6cb;
}



.check-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #4CAF50;
  font-weight: bold;
}

.password-group .form-control {
  padding-right: 30px;
}

.phone-input {
  display: flex;
  align-items: center;
}

.country-code {
  display: flex;
  align-items: center;
  background-color: #f5f8ff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 0 10px;
  margin-right: 10px;
  height: 44px;
  cursor: pointer;
}

.arrow-down {
  display: inline-block;
  width: 0;
  height: 0;
  margin-left: 5px;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid #666;
}

.phone-control {
  flex: 1;
}

.verification-group {
  display: flex;
}

.verification-control {
  flex: 1;
  margin-right: 10px;
}

.verification-btn {
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0 15px;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
}

.verification-btn:hover {
  background-color: #1E88E5;
}



.register-submit {
  margin-top: 30px;
}

.register-btn {
  width: 100%;
  padding: 12px 0;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  background-color: #2196F3;
  color: white;
  transition: background-color 0.3s;
}

.register-btn:hover {
  background-color: #1E88E5;
}

.register-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.loading-spinner {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.password-input-container {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  user-select: none;
}

.email-control {
  width: 100%;
}

/* 验证码弹窗样式 */
.captcha-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.captcha-container {
  background-color: white;
  border-radius: 8px;
  width: 320px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.captcha-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.captcha-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.captcha-content {
  padding: 20px;
}

.captcha-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  margin-bottom: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.captcha-image {
  max-width: 100%;
  max-height: 100%;
}

.captcha-loading {
  color: #999;
}

.captcha-input-group {
  margin-bottom: 10px;
}

.captcha-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.captcha-footer {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eee;
}

.captcha-refresh-btn {
  background-color: #f5f5f5;
  color: #333;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
}



.refresh-icon {
  margin-right: 5px;
  font-style: normal;
}

.captcha-confirm-btn {
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 15px;
  cursor: pointer;
  font-size: 14px;
}

.captcha-confirm-btn:hover {
  background-color: #1E88E5;
}

/* 邮箱验证码发送状态样式 */
.email-sending-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001; /* 比验证码弹窗更高 */
}

.email-sending-container {
  background-color: white;
  border-radius: 8px;
  width: 320px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.email-sending-content {
  padding: 30px 20px;
  text-align: center;
}

.email-sending-content h3 {
  margin: 15px 0 10px;
  font-size: 18px;
  color: #333;
}

.email-sending-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
  word-break: break-all;
}

.retry-info {
  color: #ff9800 !important;
  font-weight: bold;
  margin-top: 10px !important;
}

.loading-spinner-large {
  display: inline-block;
  width: 32px;
  height: 32px;
  border: 3px solid rgba(33, 150, 243, 0.3);
  border-radius: 50%;
  border-top-color: #2196F3;
  animation: spin 1s ease-in-out infinite;
}
</style> 